package com.tuocent.dagv2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tuocent.dagv2.common.AjaxResult;
import com.tuocent.dagv2.common.utils.SnowFlakeID;
import com.tuocent.dagv2.entity.ArchivesCodeFormat;
import com.tuocent.dagv2.mapper.ArchivesCodeFormatMapper;
import com.tuocent.dagv2.service.IArchivesCodeFormatService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

/**
 * <p>
 * 档号格式 服务实现类
 * </p>
 *
 * @author Vincent
 * @since 2025-07-29
 */
@Service
public class ArchivesCodeFormatServiceImpl extends ServiceImpl<ArchivesCodeFormatMapper, ArchivesCodeFormat> implements IArchivesCodeFormatService {

    @Resource
    private SnowFlakeID snowFlakeID;

    @Override
    public AjaxResult getArchivesCodeFormat(String classifyId, String id) {
        QueryWrapper<ArchivesCodeFormat> query = new QueryWrapper<ArchivesCodeFormat>()
                .eq("classify_id", classifyId);
        if (!"".equals(id)) {
            query.eq("id", id);
        }
        query.orderByAsc("pid").orderByDesc("code_model");
        return AjaxResult.success(list(query));
    }

    @Override
    public String archivesCodeFormatList(Model model, String id, String pid, String codeModel, String classifyId, String children, String parentId) {
        if (children.isEmpty()) {
            children = "0";
        }
        if ("".equals(id)) {
            id = snowFlakeID.getId();
            if (!"".equals(pid)) {
                if ("".equals(codeModel) || Integer.parseInt(codeModel) > 3 || Integer.parseInt(codeModel) < 1) {
                    model.addAttribute("message", "无效的分类模式");
                    return "/home/error";
                }
                if (count(new QueryWrapper<ArchivesCodeFormat>()
                        .eq("classify_id", classifyId)
                        .eq("pid", parentId)
                        .eq("code_model", codeModel)) > 0) {
                    model.addAttribute("message", "该级档号设定已存在");
                    return "/home/error";
                }
            } else {
                pid = id;
            }
        }
        model.addAttribute("children", children);
        model.addAttribute("codeModel", codeModel);
        model.addAttribute("pid", id);
        model.addAttribute("classifyId", classifyId);
        model.addAttribute("parentId", parentId);
        return "/basic/archivesCodeFormatList";
    }
}
